//Copyright (c) Microsoft Corporation.  All rights reserved.

#pragma once

using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;
using namespace System::Threading;

namespace  Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Controls {

public delegate void RenderHandler();

public ref class DirectControl : public System::Windows::Forms::UserControl
{
public:
    /// <summary>
    /// Constructor
    /// </summary>
    DirectControl()
		{
            SetStyle(ControlStyles::UserPaint, true);
            SetStyle(ControlStyles::AllPaintingInWmPaint, true);            
            UpdateStyles();
			killThread = gcnew System::Threading::ManualResetEvent( false );
			ThreadStart^ ts = gcnew System::Threading::ThreadStart( 
					this, 
					&Microsoft::WindowsAPICodePack::DirectX::Controls::DirectControl::RenderThreadProcedure );
			renderThread = gcnew System::Threading::Thread( ts );
			renderThread->Start();
		}


protected:
		System::Threading::Thread^ renderThread;
		System::Threading::ManualResetEvent^ killThread;


		void RenderThreadProcedure(  )
		{
			do
			{
				if (Render!= nullptr)
					Render();
				else
					System::Threading::Thread::Sleep( 1 );

			}
			while( killThread->WaitOne( 0 ) == false );
		}

       virtual void WndProc (Message %m)
            override
        {
            if(m.Msg == WM_DESTROY )
            {
				killThread->Set();
				renderThread->Join();
            }

            UserControl::WndProc(m);
        }

        virtual void OnPaintBackground(PaintEventArgs ^e) override
		{
            if (DesignMode)
            {
                e->Graphics->FillRectangle(
                    SystemBrushes::Control, 
                    System::Drawing::Rectangle(0,0,Width, Height));
            }
        }

        virtual void OnPaint(PaintEventArgs ^e)
            override
        {
            if (DesignMode)
            {               
                e->Graphics->DrawString(
                    "Direct3D Control", 
                    SystemFonts::StatusFont,
                    SystemBrushes::ControlText, 
                    (float)Width / 2, 
                    (float)Height / 2);
            }
        }

public: 
    RenderHandler^ Render;
};
}}}}
